# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from models.enhancedModel import EnhancedModel

import views.Option as optView
import models.option as optModel
import models.user as um
import decorator as dc

class OptionContr( webapp.RequestHandler ):
     @dc.decorate
     def get(self, action, *params, **kwds):
          if action == 'showAll': # DONE
               query = optModel.OptionModel.all()
               query.filter('archival =', False)
               self.response.out.write( optView.showAll(um.UserModel.userRole(),list(query)))
               
          elif action == 'delete': # DONE
            opt = EnhancedModel.queryLatest( optModel.OptionModel, ident=int(params[0])).get()
            if opt != None:
               self.response.out.write( optView.delete(um.UserModel.userRole(), opt ))
            else:
               self.response.out.write("<font color=\"red\"><b>This option has been deleted before!</b></font>")
          
          elif action == 'new': # DONE
               showError = self.request.get('error') == 'True'
               if showError :
                    self.response.out.write("<font color=\"red\"><b>There already exist option with given name!</b></font>")
               self.response.out.write(optView.new(um.UserModel.userRole()))
               
          elif action == 'populate':
              query = EnhancedModel.queryLatest( optModel.OptionModel ).filter("name =", "sameCityRadius").get()
              if (query == None):
                radiusOption = optModel.OptionModel( name = "sameCityRadius", description = "Maximum distance to assign location to city (in kilometers)", value = "40")
                radiusOption.put()
              query = EnhancedModel.queryLatest( optModel.OptionModel ).filter("name =", "maxMailTIs").get()
              if (query == None):
                radiusOption = optModel.OptionModel( name = "maxMailTIs", description = "Number of Tracking Informations attached to report sent by e-mail", value = "5")
                radiusOption.put()
              query = EnhancedModel.queryLatest( optModel.OptionModel ).filter("name =", "minimumDelay").get()
              if (query == None):
                radiusOption = optModel.OptionModel( name = "minimumDelay", description = "Shortest time considered as delay (in minutes)", value = "30")
                radiusOption.put()
              self.redirect('/options/showAll')
                
     def post(self, action, *params, **kwds):
          if action == 'new': # DONE
               name = cgi.escape(self.request.get('optName'))
               value = cgi.escape(self.request.get('optVal'))
               query = EnhancedModel.queryLatest( optModel.OptionModel )
               query.filter( 'name =', name)
               if query.count():
                    self.redirect('/options/new?error=True')
               else:
                    option = optModel.OptionModel( name = name, value = value)
                    option.put()
                    self.redirect('/options/showAll?done=True')
                    
          elif action == 'editAll': # DONE
               query = optModel.OptionModel.all()
               query.filter('archival =', False)

               for opt in query:
                  val = cgi.escape(self.request.get(str(opt.ident)))
                  if val != opt.value:
                     old = EnhancedModel.queryLatest( optModel.OptionModel, ident = opt.ident).get()
                     new = optModel.OptionModel( name = opt.name, value = val)
                     new.ident = old.ident
                     EnhancedModel.deprecateOldVersion(new, old)
                     new.put()

               self.redirect('/options/showAll?done=True')
                    
          elif action == 'delete': # DONE
               old = EnhancedModel.queryLatest( optModel.OptionModel, ident = int (params[0])).get()
               if self.request.get('delete') == "NO":
                 self.redirect('/options/showAll')
               else:
                 old.deleteInstance()
                 self.redirect('/options/showAll?done=True')
